package com.plentitude.easytrader.io;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.plentitude.easytrader.provider.WatchlistContract.DataColumns;
import com.plentitude.easytrader.provider.WatchlistContract.QuotesColumns;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.text.TextUtils;
import android.util.Log;


/**
 * Reads data from csv files
 *
 * @author team@getstarted.com.ua
 */
public class DataHandler {
	private static final String TAG = "DataHandler";
	private SQLiteDatabase db;
	private Context context;
	private final static String SEP = ",";
    
	
	public DataHandler(Context context, SQLiteDatabase db) {
		 this.context = context;
		 this.db = db;
	}
	
	// Parse data csv
	private static String T = ",";
	public void insertData() {
    	BufferedReader reader = null;
        InputStreamReader in = null;
        SQLiteStatement stmt = null;
        try{
        	in = new InputStreamReader(context.getAssets().open("data.csv"));
            reader = new BufferedReader(in, 4096);
        	db.beginTransaction();
    		String[] data = null;
    		String text = null;
    		StringBuilder sql = new StringBuilder(1024);
    		sql.append("insert into data (")
	    		.append(DataColumns.STRATEGY).append(T)
	            .append(DataColumns.TYPE).append(T)
	            .append(DataColumns.SETUP).append(T)
	            .append(DataColumns.EPIC).append(T)
	            .append(DataColumns.NAME).append(T)
	            .append(DataColumns.SECTOR).append(T)
	            .append(DataColumns.LOW_PE_VS_SECTOR).append(T)
	            .append(DataColumns.LOW_OP_MARGIN).append(T)
	            .append(DataColumns.PEG).append(T)
	            .append(DataColumns.EARNINGS_GROWS).append(T)
	            .append(DataColumns.REVENUE_GROWTH).append(T)
	            .append(DataColumns.INTEREST_COVER).append(T)
	            .append(DataColumns.NET_CURRENT_ASSETS).append(T)
	            .append(DataColumns.NET_GEARING).append(T)
	            .append(DataColumns.PROJECTED_EARNINGS).append(T)
	            .append(DataColumns.HIGH_PE_VS_SECTOR).append(T)
	            .append(DataColumns.NEG_CURRENT_ASSETS).append(T)
	            .append(DataColumns.DECREASING_REVENUES).append(T)
	            .append(DataColumns.HIGH_OP_MARGIN).append(T)
	            .append(DataColumns.FUNDAMENTAL_SCORE).append(T)
	            .append(DataColumns.MARKET).append(T)
	            .append(DataColumns.SECTOR_PERF).append(T)
	            .append(DataColumns.SECTOR_SCORE).append(T)
	            .append(DataColumns.LONG_TRADE_SCORE).append(T)
	            .append(DataColumns.SHORT_TRADE_SCORE).append(T)
	            .append(DataColumns._RSI_BUY).append(T)
	            .append(DataColumns._MACD_BUY).append(T)
	            .append(DataColumns._STOCH_BUY).append(T)
	            .append(DataColumns._EMA_BUY).append(T)
	            .append(DataColumns._RSI_SELL).append(T)
	            .append(DataColumns._MACD_SELL).append(T)
	            .append(DataColumns._STOCH_SELL).append(T)
	            .append(DataColumns._EMA_SELL).append(T)
	            .append(DataColumns.BUY_INDICATOR_NUM).append(T)
	            .append(DataColumns.SELL_INDICATOR_NUM).append(T)
	            .append(DataColumns.BROKER_CONSENSUS).append(T)
	            .append(DataColumns.LTBAT_CONSENSUS).append(T)
	            .append(DataColumns.ADDITIONAL_INFO).append(T)
	            .append(DataColumns.NEXT_SIG_STRENGTH).append(T)
	            .append(DataColumns.NEXT_SIG_DESC).append(T)
	            .append(DataColumns.REC_ENTRY_LEVEL).append(T)
	            .append(DataColumns.REC_STOP_LEVEL).append(T)
	            .append(DataColumns.TARGET_LEVEL).append(T)
	            .append(DataColumns.REWARD_RATIO).append(T)
	            .append(DataColumns.URL_CHART).append(T)
	            .append(DataColumns.URL_SECTOR_CHART).append(T)
	            .append(DataColumns.URL_EOD_CHART).append(T)
	            .append(DataColumns.URL_LIVE_CHART).append(T)
	            .append(DataColumns.URL_SUMMARY).append(T)
	            .append(DataColumns.ACTIVE_SECTOR).append(T)
	            .append(DataColumns.VOLUME_EOD).append(T)
	            .append(DataColumns.COMPANY_PROFILE).append(T)
	            .append(DataColumns.ALERTS).append(T)
	            .append(DataColumns.NEWS).append(T)
	            .append(DataColumns.OUTLOOK).append(T)
	            .append(DataColumns.PARAMS_AND_SETTINGS).append(T)
	            .append(DataColumns.DEFAULT_FIELD_VALUES)
                .append(") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            stmt = db.compileStatement(sql.toString());
    		while(((text = reader.readLine()) != null)) {
            	data = text.split(SEP);
            	if(!TextUtils.isEmpty(data[0])) {
                	for(int i=0; i<57; i++) {
                		try { stmt.bindString(i+1, data[i]); } catch(Exception e) { stmt.bindNull(i); }
                	}
            	}
            	stmt.execute();
            }
            db.setTransactionSuccessful();
        } catch(Exception e) {
        	Log.e(TAG, e.toString());
        } finally {
        	try {
        		db.endTransaction();
        		stmt.close();
        		if(reader != null) {
                    reader.close();
                }
                if(in != null) {
                	in.close();
                }
            } catch(Exception e) {
            	Log.e(TAG, e.toString());
            }
        }
    }
	
	// Parse quote.csv
    public void insertQuotes() {
    	BufferedReader reader = null;
        InputStreamReader in = null;
        SQLiteStatement stmt = null;
        try{
        	in = new InputStreamReader(context.getAssets().open("quote.csv"));
            reader = new BufferedReader(in, 1024);
        	db.beginTransaction();
    		String[] data = null;
    		String text = null;
    		StringBuilder sql = new StringBuilder(128);
    		sql.append("insert into quotes (")
    			.append(QuotesColumns.SYMBOL).append(T)
    			.append(QuotesColumns.PRICE).append(T)
    			.append(QuotesColumns.DATE).append(T)
    			.append(QuotesColumns.TIME).append(T)
    			.append(QuotesColumns.CHANGE).append(T)
    			.append(QuotesColumns.OPEN).append(T)
    			.append(QuotesColumns.HIGH).append(T)
    			.append(QuotesColumns.LOW).append(T)
    			.append(QuotesColumns.VOLUME)
    			.append(") values (?,?,?,?,?,?,?,?,?)");
    		stmt = db.compileStatement(sql.toString());
            while(((text = reader.readLine()) != null)) {
                if(!(text.length() > 1024)) {
                	data = text.split(SEP);
                	if(!TextUtils.isEmpty(data[0])) {
	                	stmt.bindString(1, data[0].replace("\"", "")); // symbol
	                	try { stmt.bindDouble(2, Double.valueOf(data[1])); } catch(Exception e) { stmt.bindNull(2); }   // price
	                	try { stmt.bindString(3, data[2].replace("\"", "")); } catch(Exception e) { stmt.bindNull(3); } // date 
	                	try { stmt.bindString(4, data[3].replace("\"", "")); } catch(Exception e) { stmt.bindNull(4); } // time
	                	try { stmt.bindString(5, data[4]); } catch(Exception e) { stmt.bindNull(5); } 			 	    // change
	                	try { stmt.bindDouble(6, Double.valueOf(data[5])); } catch(Exception e) { stmt.bindNull(6); }   // open
	                	try { stmt.bindDouble(7, Double.valueOf(data[6])); } catch(Exception e) { stmt.bindNull(7); }   // high
	                	try { stmt.bindDouble(8, Double.valueOf(data[7])); } catch(Exception e) { stmt.bindNull(8); }   // low
	                	try { stmt.bindDouble(9, Double.valueOf(data[8])); } catch(Exception e) { stmt.bindNull(9); }   // volume
                	}
                	stmt.execute();
                }
            }
            db.setTransactionSuccessful();
        } catch(Exception e) {
        	Log.e(TAG, e.toString());
        } finally {
        	try {
        		db.endTransaction();
        		stmt.close();
        		if(reader != null) {
                    reader.close();
                }
                if(in != null) {
                	in.close();
                }
            } catch(Exception e) {
            	Log.e(TAG, e.toString());
            }
        }
    }
    
}
